import { DictType } from "./../utils/cacheUtil";
import { reactive } from "vue";
import { Dict, getDictList } from "@/utils/cacheUtil";
import { Variable } from "@/api/interface/iot";
export const useDict = () => {
	const state = reactive({
		//按类型区分字典列表
		dictTypeMap: {} as { [key: string]: Dict[] },
		//按类型区分字典列表
		dictMap: {} as { [key: string]: Dict },
		//按变量区分字典列表(sn_key)
		variableDictMap: {} as { [key: string]: Dict[] },
		//按设备区分告警列表
		deviceAlarmList: {} as { [key: string]: Dict[] },
		allAlarmTypeList: [] as Dict[]
	});

	getDictList(DictType.AlarmType).then(res => {
		let keys = new Set();
		res.forEach(item => {
			if (!keys.has(item.key)) {
				keys.add(item.key);
				state.allAlarmTypeList.push(item);
			}
		});
	});
	//字典key对应一个字典项
	const getDictMap = (type: string) => {
		getDictList(type).then((dictList: Dict[]) => {
			state.dictTypeMap[type] = dictList;
			dictList.forEach((item: Dict) => {
				state.dictMap[item.key] = item;
			});
		});
	};

	//一个变量对应一组字典
	const loadVariableDict = async (variable: Variable.ResVariable) => {
		let dictType = variable.param?.dict;
		if (!dictType) {
			return;
		}
		let key = variable.sn + "_" + variable.key;
		if (!state.variableDictMap[key]) {
			state.variableDictMap[key] = await getDictList(dictType);
		}
	};

	return { loadVariableDict, getDictMap, ...toRefs(state) };
};
